//
//  ACRecommedController.m
//  MonitoringSystem
//
//  Created by JiaKang.Zhong on 16/7/10.
//  Copyright © 2016年 Interlube. All rights reserved.
//

#import "ACRecommedController.h"
#import "ACRecommedHeadView.h"
#import "ACRecommedViewCell.h"
#import "NetRequestClass.h"
#import "UtilToolsClass.h"
#import "ACCustomAlertView.h"
#import "YLZHoledView.h"
@interface ACRecommedController ()<UITableViewDelegate,UITableViewDataSource>{
    BOOL isEdit;// 是否是编辑模式
    NSInteger tagStr; // 选中行的对应的pk1
    NSInteger currentIndex;// 记忆选中行
}
@property (strong, nonatomic)  UITableView *tableView;
@property(nonatomic,strong) NSMutableArray * defaultCongfigArr;// 默认配置
@property(nonatomic,strong) NSMutableArray * customConfigArr;// 自定义配置
@property(nonatomic,strong) NSString * configPk1;// 配置PK1
@property(nonatomic,weak) UIImageView * cinputView;
@property(nonatomic,weak) YLZHoledView * ylzGuidView;
- (IBAction)rightCloseBtnCallBack:(id)sender;
- (IBAction)leftFinashCallBack:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UIButton *ceditConfig;
@property (weak, nonatomic) IBOutlet UILabel *lblTitleName;

@end

@implementation ACRecommedController

static NSString * identifier = @"cell-identifier";


- (NSMutableArray *)customConfigArr{
    if (!_customConfigArr) {
        _customConfigArr = [NSMutableArray array];
    }
    return _customConfigArr;
}

- (NSMutableArray *)defaultCongfigArr{
    if (!_defaultCongfigArr) {
        _defaultCongfigArr = [NSMutableArray array];
    }
    return _defaultCongfigArr;
}


- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 66, SCREEN_WIDTH, SCREEN_HEIGHT - 66) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor colorWithRed:31/ 255.0 green:36 / 255.0 blue:46 / 255.0 alpha:1];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
       [_tableView registerNib:[UINib nibWithNibName:@"ACRecommedViewCell" bundle:nil] forCellReuseIdentifier:identifier];
        _tableView.rowHeight = 60;
    }
    return _tableView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    currentIndex = -10;
    isEdit = true;
    self.configPk1 = @"";
    tagStr = 0;
    [self translateLanguage];
    
    if([[UD objectForKey:@"maskLayerGuid8"] intValue]){
        // 推荐配置
        YLZHoledView * tView = [[YLZHoledView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        tView.dimingColor = [UIColor clearColor];
        [[UIApplication sharedApplication].keyWindow addSubview:tView];
        self.ylzGuidView = tView;
        
        UIImageView * guidLableView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"GuidTJ"]];
        guidLableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        [tView addSubview:guidLableView];
        
        UIButton * nextBtn = [[UIButton alloc] init];
        [nextBtn setImage:[UIImage imageNamed:@"Guiderwwozhidaole"] forState:UIControlStateNormal];
        [nextBtn sizeToFit];
        nextBtn.tag = 0;
        nextBtn.center = CGPointMake(SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.9);
        [tView addSubview:nextBtn];
        [nextBtn addTarget:self action:@selector(rightCloseBtnCallBack:) forControlEvents:UIControlEventTouchUpInside];
        
    }else{
        [self requesData];
    }
}


- (void) translateLanguage{
    self.lblTitleName.text = NSLocalizedString(@"推荐配置",nil);
    [self.ceditConfig setTitle:NSLocalizedString(@"编辑",nil) forState:UIControlStateNormal];
}


#pragma mark  请求数据
- (void) requesData{
    __weak typeof(self)weakSelf = self;
    [[UtilToolsClass getUtilTools]  addDoLoading];
    [NetRequestClass requestWithUrlForGetDefaultConfig:self andUrl:[REQUESTHEADER stringByAppendingString:@"deviceList/deviceRecomConfig.asp"] andParam:@{@"i_imei":self.imei} success:^(NSDictionary *result) {
        [[UtilToolsClass getUtilTools]  removeDoLoading];
        [weakSelf initWithUI:result];
    } failure:^(NSString *failure) {
        [[UtilToolsClass getUtilTools]  removeDoLoading];
    }];
}


- (void) initWithUI:(NSDictionary *) resultDic{
    
    self.customConfigArr = [resultDic[@"customConfig"] mutableCopy];
    self.defaultCongfigArr = [resultDic[@"config"] mutableCopy];
    [self.view addSubview:self.tableView];
}

#pragma mark - Table view data source
// 组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

// 行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section == 0) {
        return self.defaultCongfigArr.count;//
    }
    return self.customConfigArr.count;//
}

// 头部高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}


// 头部视图
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        // 推荐配置
        ACRecommedHeadView * headView = [[ACRecommedHeadView alloc] initWithTitle:NSLocalizedString(@"推荐",nil) withImage:[UIImage imageNamed:@"icon-tuijian"]];
        return headView;
    }else if (section == 1){
        // 自定义配置
        ACRecommedHeadView * headView = [[ACRecommedHeadView alloc] initWithTitle:NSLocalizedString(@"自定义",nil) withImage:[UIImage imageNamed:@"icon-zidingyi"]];
        return headView;
    }
    return [UIView new];
}


// 行样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ACRecommedViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ACRecommedViewCell" owner:nil options:nil] lastObject];
    }
   
    NSDictionary * tempDic ;
    if (indexPath.section == 0) {
        tempDic = self.defaultCongfigArr[indexPath.row];
        
    }else{
        tempDic = self.customConfigArr[indexPath.row];
       
    }
    cell.configDic = tempDic;
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


// 选中对应的行后
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (!self.isEmployer) {
        //存在管理者 UIAlertView
        ACCustomAlertView * alertView = [[ACCustomAlertView alloc] initAlertViewWithFrame:CGRectMake(SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.5 - 80, SCREEN_WIDTH * 0.8, 160) andSuperView:self.view];
        [alertView createTitle:NSLocalizedString(@"提示",nil) message:[NSString stringWithFormat:@"%@:+%@ %@%@",NSLocalizedString(@"该设备已被",nil),self.zone,self.employer,NSLocalizedString(@"用户绑定",nil)] calcelButton:@"" okButton:NSLocalizedString(@"确定",nil)];
        [[UIApplication sharedApplication].keyWindow addSubview:alertView];
        return;
    }
    if (self.cinputView) {
        [self.cinputView removeFromSuperview];
    }
      ACRecommedViewCell *cell =  [tableView cellForRowAtIndexPath:indexPath];
    NSInteger cIndex = indexPath.section * 10 + indexPath.row;
    if (cIndex != currentIndex) {
        // 选中了同一行
        UIImageView * inputView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon-selected"]];
        inputView.center = CGPointMake(cell.bounds.size.width - 30, 30);
        [inputView sizeToFit];
        [cell addSubview:inputView];
        self.cinputView = inputView;
    }
    NSString * tempStr = @"";
    if (indexPath.section == 0) {
        ;
        tempStr =  [NSString stringWithFormat:@"%@",self.defaultCongfigArr[indexPath.row][@"configPk"]];
        tagStr = 0;
    }else{
        tempStr =   [NSString stringWithFormat:@"%@",self.customConfigArr[indexPath.row][@"configPk"]];
        tagStr = 1;
    }
    self.configPk1 = tempStr;
    currentIndex = cIndex;
}

// 返回单元格的风格
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"indexPath.row :%ld",(long)indexPath.row);

    if (indexPath.section == 0 && indexPath.row < self.defaultCongfigArr.count) {
        return UITableViewCellEditingStyleNone;
      
    }
     return UITableViewCellEditingStyleDelete;
}

// 删除行
-(void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isEmployer) {
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            //  删除单元格的某一行时，在用动画效果实现删除过程
            NSInteger configIndex = indexPath.row;
            NSString * configStr =  [NSString stringWithFormat:@"%@",self.customConfigArr[configIndex][@"configPk"]];
            [self.customConfigArr removeObjectAtIndex:configIndex];
            self.configPk1 = @"";
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            
            [NetRequestClass requestWithURLForDelegateRecommdConfig:self andUrl:[REQUESTHEADER stringByAppendingString:@"deviceList/deleteRecommendConfig.asp"] andParam:@{@"configPk":configStr} success:^(NSInteger result) {
                if (!result) {
//                    [UtilToolsClass addDisapperAlert:@"" withMessage:@"删除成功"];
                }
                
            } failure:^(NSString *failure) {
                [UtilToolsClass addDisapperAlert:@"" withMessage:failure];
            }];
        }
    }else{
        //存在管理者 UIAlertView
        ACCustomAlertView * alertView = [[ACCustomAlertView alloc] initAlertViewWithFrame:CGRectMake(SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.5 - 80, SCREEN_WIDTH * 0.8, 160) andSuperView:self.view];
        [alertView createTitle:NSLocalizedString(@"提示",nil) message:[NSString stringWithFormat:@"%@:+%@ %@%@",NSLocalizedString(@"该设备已被",nil),self.zone,self.employer,NSLocalizedString(@"用户绑定",nil)] calcelButton:@"" okButton:NSLocalizedString(@"确定",nil)];
        [[UIApplication sharedApplication].keyWindow addSubview:alertView];
        
    }
}

- (void)returnText:(GetDeviceConfig)block{
    self.pushDeviceName = block;
}
// 返回配置对应的pk值
- (IBAction)rightCloseBtnCallBack:(id)sender {
    [self.ylzGuidView removeFromSuperview];
    __weak typeof(self) weakSelf = self;
    [self dismissViewControllerAnimated:YES completion:^{
        weakSelf.pushDeviceName(@{@"configPk":weakSelf.configPk1,@"tagStr":@(tagStr)});
    }];
}

- (IBAction)leftFinashCallBack:(UIButton *)sender {
   
    if (isEdit) {
            [sender setTitle:NSLocalizedString(@"完成",nil) forState:UIControlStateNormal];
         [self.tableView setEditing:YES animated:YES];
        isEdit = false;
    }else{
        [sender setTitle:NSLocalizedString(@"编辑",nil) forState:UIControlStateNormal];
         [self.tableView setEditing:NO animated:YES];
        isEdit = true;
    }
    
}
@end
